package it.sd.pwframework.admin.converter;

import java.util.Iterator;
import java.util.LinkedList;

public class ConverterUtilityString {

	private static final char PIPE		= '|';
	private static final char ESCAPE 	= '#';
	
	public static String serialize(LinkedList<String> valori) throws Exception {

		StringBuffer b = new StringBuffer();

		for (Iterator<String> iterator = valori.iterator(); iterator.hasNext();) {
			String string = (String) iterator.next();
			
			if (b.length()!=0) b.append(PIPE);
			b.append(escape(string));
			
		}
		
		return b.toString();

	}
	
	public static LinkedList<String> deSerialize(String valore) throws Exception {

		LinkedList<String> valori = new LinkedList<String>();
		StringBuffer v= new StringBuffer();
		
		for (int i = 0; i < valore.length(); i++) {
			char c = valore.charAt(i);
			if (c==ESCAPE) {
				i++;
				v.append(valore.charAt(i));
			} else if (c==PIPE) {
				valori.add(v.toString());
				v.replace(0, v.length(), "");
			} else {
				v.append(c);
			}
		}
		
		valori.add(v.toString());
		
		return valori;

	}
	
	public static String escape(String valore) {
		
		StringBuffer b = new StringBuffer();
		
		if (valore!=null) {
			for (int i = 0; i < valore.length(); i++) {
				char c = valore.charAt(i);
				if (c == PIPE) {
					b.append(ESCAPE);
				} else if (c == ESCAPE) {
					b.append(ESCAPE); 
				}
				b.append(c);
			}
		}
		
		return b.toString();
		
	}


	
	public static void main(String[] args) {
		
		try {
			LinkedList<String> valori = new LinkedList<String>();
			valori.add("aa");
			valori.add("a|e");
			valori.add("a\\|\\\\ii||");
			valori.add("aeee");
			valori.add("aererer");
			 
			System.out.println(valori);
			String valore = serialize(valori);
			System.out.println(valore);
			
			valori = deSerialize(valore);
			System.out.println(valori);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

}
